package com.example.demo.zaqizabatest;

import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.*;

/**
 * @ClassName FileDownloader
 * @Author l42142
 * @Date 2021/3/3 14:11
 * @Description TODO
 * @Version 1.0
 **/
public class FileDownloader {
    // 线程池
    private final ExecutorService executor = Executors.newFixedThreadPool(10);

    public boolean download(final URL url, final Path path) {
        Future<Path> future = executor.submit(new Callable<Path>() { //submit提交任务
            @Override
            public Path call() throws Exception {
                InputStream is = url.openStream();
                Files.copy(is, path, StandardCopyOption.REPLACE_EXISTING);
                return path;
            }
        });
        try {
            return future.get() != null ? true : false;
        } catch (ExecutionException e) {
            return false;
        } catch (InterruptedException e) {
            return false;
        }
    }

    public void close() {//当不再使用FileDownloader类的对象时，应该使用close方法关闭其中包含的ExecutorService接口的实现对象，否则虚拟机不会退出，占用内存不释放
        executor.shutdown();// 发出关闭请求，此时不会再接受新任务
        try {
            if (!executor.awaitTermination(3, TimeUnit.MINUTES)) {// awaitTermination 来等待一段时间，使正在执行的任务或等待的任务有机会完成
                executor.shutdownNow();// 如果等待时间过后还有任务没完成，则强制结束
                executor.awaitTermination(1, TimeUnit.MINUTES);// 再等待一段时间，使被强制结束的任务完成必要的清理工作
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
